package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.vo.WeiBoResponseVo;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExistException;
import com.atguigu.gulimall.member.exception.UsernameExistException;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.MemberRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {


    @Autowired
    MemberLevelDao memberLevelDao;

    @Autowired
    BCryptPasswordEncoder encoder;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRegisterVo vo) {
        if (!checkPhoneUnique(vo.getPhone())) {
//            直接抛异常
            throw new PhoneExistException();
        }

        if (!checkUsernameUnique(vo.getUsername())) {
            throw new UsernameExistException();
        }


        MemberLevelEntity level = memberLevelDao.getDefaultLevel();

        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setUsername(vo.getUsername());
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setLevelId(level.getId());
//        密码加密存储
        memberEntity.setPassword(encoder.encode(vo.getPassword()));
//        TODO 其他默认信息

        baseMapper.insert(memberEntity);
    }

    @Override
    public boolean checkPhoneUnique(String phone) {
        return baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone)) > 0;
    }

    @Override
    public boolean checkUsernameUnique(String username) {
        return baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username)) > 0;
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginAcct = vo.getLoginAcct();
        String password = vo.getPassword();

//        查询数据库
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginAcct).or().eq("mobile", loginAcct));
        if (memberEntity == null) {
//            登陆失败
            return null;
        } else {
            if (!encoder.matches(password, memberEntity.getPassword())) {
                return null;
            }
            memberEntity.setPassword(null);
            return memberEntity;
        }
    }

    @Override
    public MemberEntity weiboLogin(WeiBoResponseVo vo) {
        String uid = vo.getUid();
//        判断uid是否已经关联了账户
        MemberEntity member = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (member != null) {
//            已经有账户了，更新令牌和过期时间
            MemberEntity memberEntity = new MemberEntity();
            memberEntity.setId(member.getId());
            memberEntity.setAccessToken(vo.getAccess_token());
            memberEntity.setExpiresIn(Long.toString(vo.getExpires_in()));
            baseMapper.updateById(memberEntity);

            member.setAccessToken(vo.getAccess_token());
            member.setExpiresIn(Long.toString(vo.getExpires_in()));
            return member;
        }
//        需要注册一个
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setSocialUid(vo.getUid());
        memberEntity.setAccessToken(vo.getAccess_token());
        memberEntity.setExpiresIn(Long.toString(vo.getExpires_in()));
//        查询用户社交账户信息
        try {

            HashMap<String, String> params = new HashMap<>();
            params.put("access_token", vo.getAccess_token());
            params.put("uid", vo.getUid());
            String result = HttpUtils.sendGet("https://api.weibo.com/2/users/show.json", params);
            if (result != null) {
                JSONObject object = JSON.parseObject(result);
                String nickname = object.getString("name");
                String gender = object.getString("gender");
                memberEntity.setNickname(nickname);
                memberEntity.setGender("m".equals(gender) ? 1 : 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        baseMapper.insert(memberEntity);
        return memberEntity;
    }

}